import jsrsasign from "jsrsasign";
import request from "@/utils/request";

const toast = (message) => {
  uni.showToast({
    icon: "none",
    title: message,
    duration: 2000,
  });
};

// 页面路由跳转
const jumpPage = (page) => {
  uni.navigateTo({
    url: page,
  });
};

// 获取公钥
const getPublicKey = (password) => {
  return new Promise(async (resolve, reject) => {
    const res = await request.get("publicKey");
    console.log(res);
    // 密码加密
    let modulus = res.data.modulus;
    let exponent = res.data.exponent;
    let rsaKey = new jsrsasign.RSAKey();
    rsaKey.setPublic(jsrsasign.b64tohex(modulus), jsrsasign.b64tohex(exponent));
    let encrypt = jsrsasign.hex2b64(rsaKey.encrypt(password));
    // 请求Cookie
    let setCookie = res.headers["set-cookie"][0];
    let cookie = setCookie.substring(
      setCookie.indexOf("JSESSIONID"),
      setCookie.indexOf(";")
    );
    // 获取 csrftoken
    const csrftoken = await getCsrfToken(cookie);
    resolve({ encrypt, cookie, csrftoken });
  });
};

// 获取csrftoken
const getCsrfToken = (cookie) => {
  return new Promise(async (resolve, reject) => {
    const res = await request.post("csrfToken", { cookie });
    const index = res.data.indexOf("csrftoken");
    let html = res.data.substr(index + 1, 150);
    let token = html.substring(0, html.indexOf("/>"));
    let csrftoken = token.substr(token.indexOf("value"));
    token = csrftoken.substr(csrftoken.indexOf("=")).slice(2, -1);
    resolve(token);
  });
};

// 获取周次
const getWeek = (dateTime, startDate) => {
  let startTime = startDate.split("/");
  let temptTime = new Date(dateTime);
  let weekday;
  temptTime.getDay() == 0 ? (weekday = 7) : (weekday = temptTime.getDay());

  temptTime.setDate(temptTime.getDate() - weekday + 6);
  let firstDay = new Date(
    Number(startTime[0]),
    Number(startTime[1]) - 1,
    Number(startTime[2])
  );
  let spendDay = 1;
  if (firstDay.getDay() != 0) {
    spendDay = 7 - firstDay.getDay() + 1;
  }
  firstDay = new Date(
    Number(startTime[0]),
    Number(startTime[1]) - 1,
    Number(startTime[2]) + spendDay
  );
  let d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000);
  let result = Math.ceil(d / 7);
  return result + 1;
};

export default { toast, jumpPage, getPublicKey, getWeek };
